Introduction to Stored Programs in MySQL
Course: MySQL Training Course
Topic: Introduction to Stored Programs in MySQL
Course Link: MySQL Training Course
Demo Link: Register for a Course Demo
1. Introduction to Stored Programs in MySQL
Stored programs in MySQL are database objects that contain SQL statements and programming logic stored on the database server for later execution. Instead of writing the same SQL statements repeatedly in an application, developers can organize frequently used operations into reusable programs.
Stored programs help implement business rules, automate database operations, perform calculations, validate data, and manage complex workflows directly within MySQL.
For example, an online shopping application may need to calculate an order total, update inventory, record payment information, and create transaction logs. Some of these operations can be implemented using stored procedures, functions, triggers, or scheduled events.
MySQL's main stored program types are stored procedures, stored functions, triggers, and events. Views are also stored database objects, but they are not classified as stored programs in the same technical sense.
Example of a Repeated SQL Operation
Suppose an application repeatedly needs to retrieve the details of a particular customer. A query might be written as follows:
SELECT customer_id, customer_name, email
FROM customers
WHERE customer_id = 101;
If many applications need this operation, the SQL logic can be organized into a stored procedure. Authorized applications can then call the procedure instead of maintaining separate copies of the same database logic.
2. Learning Objectives
After completing this topic, learners should be able to:
- Define stored programs in MySQL.
- Understand why stored programs are used in database applications.
- Identify the different types of stored programs.
- Differentiate stored procedures and stored functions.
- Understand triggers and scheduled events.
- Recognize basic SQL syntax for creating and executing stored programs.
- Understand parameters, variables, conditional statements, and loops.
- Learn how to inspect, modify, and remove stored program objects.
- Understand basic security, performance, and maintenance considerations.
- Apply stored programs to practical database scenarios.
3. What Is a Stored Program?
A stored program is a collection of SQL statements and supported procedural logic that is saved in a MySQL database and executed when its defined conditions are met or when it is explicitly invoked.
Depending on its type, a stored program may execute when an application calls it, when a database table experiences a particular event, or when a scheduled time is reached.
Key Characteristics
- Stored on the server: The program definition is maintained by the database server.
- Reusable: The same logic can be executed multiple times.
- Database-oriented: Stored programs can work directly with database tables and SQL statements.
- Procedural logic: Supported constructs include variables, conditions, loops, and compound statements.
- Controlled execution: Database privileges determine which users can create or execute particular objects.
- Centralized business rules: Common operations can be maintained in one database location rather than duplicated across applications.
Example
DELIMITER //
CREATE PROCEDURE GetAllCustomers()
BEGIN
SELECT customer_id, customer_name, email
FROM customers;
END //
DELIMITER ;
This example creates a stored procedure named GetAllCustomers. When the procedure is called, MySQL executes its SELECT statement and returns the result set to the client.
4. Types of Stored Programs in MySQL
MySQL supports four primary stored program types: stored procedures, stored functions, triggers, and events.
| Type |
Purpose |
How It Executes |
Example Use Case |
| Stored Procedure |
Performs one or more database operations. |
Explicitly called using CALL. |
Registering a customer or processing an order. |
| Stored Function |
Calculates and returns a value. |
Called within an expression or SQL statement, subject to applicable restrictions. |
Calculating a discount or tax amount. |
| Trigger |
Responds to a specified table event. |
Automatically executes when the defined event occurs. |
Recording changes in an audit table. |
| Event |
Executes SQL logic according to a schedule. |
Runs through the MySQL Event Scheduler. |
Performing a daily database maintenance task. |
These objects serve different purposes. A procedure is generally suitable for a multi-step operation, a function for returning a calculated value, a trigger for reacting to table changes, and an event for time-based automation.
5. Stored Procedures
A stored procedure is a named collection of SQL statements saved in a database. It can perform operations such as retrieving records, inserting data, updating tables, validating inputs, and coordinating several SQL statements.
5.1 Creating a Stored Procedure
The basic syntax is:
CREATE PROCEDURE procedure_name()
BEGIN
SQL statements;
END;
The following example creates a procedure that retrieves customer records.
DELIMITER //
CREATE PROCEDURE DisplayCustomers()
BEGIN
SELECT customer_id, customer_name, email
FROM customers;
END //
DELIMITER ;
Explanation:
CREATE PROCEDURE creates a stored procedure.
DisplayCustomers is the procedure name.
BEGIN starts the compound statement block.
- The SELECT statement retrieves customer information.
END marks the end of the procedure body.
DELIMITER // temporarily changes the client delimiter so semicolons inside the procedure body do not prematurely terminate the CREATE statement.
The DELIMITER command is a command supported by MySQL client tools such as the MySQL command-line client. It is not itself a SQL statement sent to the server in the same way as CREATE PROCEDURE.
5.2 Executing a Stored Procedure
Use the CALL statement to execute a stored procedure.
CALL DisplayCustomers();
MySQL runs the procedure's statements and returns the selected customer records to the client.
5.3 Stored Procedures with Input Parameters
Parameters allow a procedure to accept values from the calling application. This makes a procedure more flexible than one that always uses fixed values.
DELIMITER //
CREATE PROCEDURE GetCustomerById(IN p_customer_id INT)
BEGIN
SELECT customer_id, customer_name, email
FROM customers
WHERE customer_id = p_customer_id;
END //
DELIMITER ;
Call the procedure with a customer ID:
CALL GetCustomerById(101);
The parameter p_customer_id receives the value 101, which is used in the WHERE clause.
5.4 Types of Procedure Parameters
| Parameter Mode |
Description |
Typical Use |
| IN |
Provides an input value to the procedure. |
Passing a customer ID or order amount. |
| OUT |
Returns a value through an output parameter. |
Returning the number of matching records. |
| INOUT |
Accepts an initial value and can return a modified value. |
Updating a supplied counter. |
5.5 Example of an OUT Parameter
DELIMITER //
CREATE PROCEDURE CountCustomers(OUT p_total INT)
BEGIN
SELECT COUNT(*)
INTO p_total
FROM customers;
END //
DELIMITER ;
Execute the procedure and inspect its output parameter:
CALL CountCustomers(@customer_total);
SELECT @customer_total;
The procedure counts the rows in the customers table and assigns the result to the output parameter. The caller can then read the value through the session variable.
6. Stored Functions
A stored function is a named database routine that returns a value. Functions are useful when a calculation or transformation needs to be reused in SQL expressions.
Unlike a procedure, which is invoked using CALL, a stored function is normally invoked by writing its name in an expression. Stored functions must declare a return type and return a compatible value.
6.1 Basic Syntax
CREATE FUNCTION function_name(parameters)
RETURNS data_type
[characteristics]
BEGIN
-- Statements
RETURN value;
END;
6.2 Example: Calculating a Discount
DELIMITER //
CREATE FUNCTION CalculateDiscount(
p_amount DECIMAL(10,2),
p_rate DECIMAL(5,2)
)
RETURNS DECIMAL(10,2)
DETERMINISTIC
NO SQL
BEGIN
RETURN p_amount * p_rate / 100;
END //
DELIMITER ;
Use the function in a SELECT statement:
SELECT CalculateDiscount(1000.00, 10.00) AS discount_amount;
The result is 100.00 because 10 percent of 1000 is 100.
Important: The DETERMINISTIC characteristic means the function is declared to return the same result for the same arguments. Use it only when that statement accurately describes the function's behavior. The NO SQL characteristic declares that the function contains no SQL data-access statements.
6.3 Characteristics of Stored Functions
- A function declares a return data type.
- A function returns a value through RETURN.
- It can be used in expressions where the function's return type is appropriate.
- Its behavior is subject to MySQL stored-function restrictions.
- It should be designed to perform a clearly defined calculation or transformation.
7. Stored Procedures vs Stored Functions
| Feature |
Stored Procedure |
Stored Function |
| Creation statement |
CREATE PROCEDURE |
CREATE FUNCTION |
| Execution |
CALL procedure_name() |
function_name() within an expression |
| Return behavior |
Can return results through OUT/INOUT parameters or result sets. |
Returns a value using RETURN. |
| Return type declaration |
No single required scalar return type. |
Requires RETURNS data_type. |
| Common use |
Multi-step operations and workflows. |
Reusable calculations and transformations. |
| Use in SELECT expressions |
Not called as a scalar expression. |
Can be used in appropriate SQL expressions. |
| Restrictions |
Subject to stored procedure rules. |
Subject to additional stored-function restrictions. |
8. Triggers in MySQL
A trigger is a stored program associated with a table. It automatically executes when a specified INSERT, UPDATE, or DELETE event occurs for that table.
Triggers are useful for auditing changes, enforcing certain data rules, and maintaining related information when rows are modified.
8.1 Trigger Timing
- BEFORE: Executes before the triggering row operation.
- AFTER: Executes after the triggering row operation.
8.2 Trigger Events
| Event |
When It Fires |
Example |
| INSERT |
When a row is inserted. |
Recording newly created records. |
| UPDATE |
When an existing row is updated. |
Tracking changes to a customer's email address. |
| DELETE |
When a row is deleted. |
Auditing deleted records. |
8.3 Example: Recording Customer Insertions
First, create an audit table:
CREATE TABLE customer_audit (
audit_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
action_name VARCHAR(20) NOT NULL,
action_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Create a trigger that records inserted customer rows:
DELIMITER //
CREATE TRIGGER AfterCustomerInsert
AFTER INSERT ON customers
FOR EACH ROW
BEGIN
INSERT INTO customer_audit (customer_id, action_name)
VALUES (NEW.customer_id, 'INSERT');
END //
DELIMITER ;
When a new customer is inserted, the trigger records the new customer's ID and the INSERT action in the audit table.
Understanding NEW: In an INSERT trigger, NEW.column_name refers to the value of the newly inserted row. In an UPDATE trigger, NEW refers to the new row values and OLD refers to the previous values. In a DELETE trigger, OLD refers to the deleted row values.
9. Events in MySQL
An event is a stored database object that executes SQL statements according to a defined schedule. Events can automate recurring tasks without requiring an application to send a request at each scheduled time.
Examples include generating periodic summaries, removing expired temporary data, and performing scheduled maintenance operations.
9.1 Example: Creating a Scheduled Event
The following example creates an event that runs once a day and inserts a timestamp into a maintenance log.
CREATE TABLE maintenance_log (
log_id INT AUTO_INCREMENT PRIMARY KEY,
message VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE EVENT DailyMaintenanceLog
ON SCHEDULE EVERY 1 DAY
DO
INSERT INTO maintenance_log (message)
VALUES ('Daily maintenance event executed');
For an event to execute, the MySQL Event Scheduler must be enabled. Check its status with:
SHOW VARIABLES LIKE 'event_scheduler';
Depending on server configuration and permissions, an administrator may need to enable the scheduler. A typical administrative command is:
SET GLOBAL event_scheduler = ON;
This requires the appropriate privilege, and the setting's persistence depends on the server configuration. Do not assume the event will run simply because its definition was created successfully.
10. Understanding the DELIMITER Command
Stored program bodies commonly contain multiple SQL statements separated by semicolons. When using an interactive MySQL client, the semicolon is also commonly used to mark the end of a complete command.
The DELIMITER command changes the client's statement terminator temporarily so the entire CREATE statement can be submitted as one command.
Example
DELIMITER //
CREATE PROCEDURE ExampleProcedure()
BEGIN
SELECT 'First statement';
SELECT 'Second statement';
END //
DELIMITER ;
Here, // marks the end of the CREATE PROCEDURE command for the client. The semicolons inside BEGIN and END continue to separate individual statements within the procedure.
Note: DELIMITER is a client command rather than part of the stored program definition. Some database drivers and graphical SQL tools handle statement submission differently, so follow the syntax conventions of the tool being used.
11. Compound Statements: BEGIN and END
A compound statement groups multiple SQL statements into one block. Stored procedures, functions, triggers, and events can use BEGIN and END to organize their logic where permitted.
BEGIN
DECLARE v_total INT DEFAULT 0;
SET v_total = 10;
SELECT v_total;
END
In a stored program, the BEGIN...END block can contain declarations and executable statements in an order governed by MySQL's syntax rules. For example, local variable declarations must appear before executable statements in the same block.
12. Variables in Stored Programs
Variables store temporary values while a stored program executes. They are useful for calculations, comparisons, intermediate results, and controlling program flow.
12.1 Declaring a Local Variable
DECLARE v_count INT DEFAULT 0;
Local variables are declared inside an appropriate compound statement block.
12.2 Assigning a Value
SET v_count = 25;
12.3 Using a Variable
DELIMITER //
CREATE PROCEDURE ShowExampleValue()
BEGIN
DECLARE v_count INT DEFAULT 25;
SELECT v_count AS example_value;
END //
DELIMITER ;
Execute the procedure:
CALL ShowExampleValue();
MySQL returns a result containing the value 25.
12.4 Local Variables vs Session Variables
| Variable Type |
Example |
Scope |
| Local variable |
DECLARE v_total INT; |
Within its stored-program block and scope. |
| Session variable |
SET @total = 100; |
Available during the current database session. |
13. Conditional Statements in Stored Programs
Conditional statements allow stored programs to choose between different actions depending on whether a condition is true or false.
13.1 IF Statement
IF condition THEN
statements;
ELSEIF another_condition THEN
statements;
ELSE
statements;
END IF;
13.2 Example: Categorizing an Order Amount
DELIMITER //
CREATE PROCEDURE CheckOrderAmount(IN p_amount DECIMAL(10,2))
BEGIN
IF p_amount >= 10000 THEN
SELECT 'High-value order' AS order_category;
ELSEIF p_amount >= 1000 THEN
SELECT 'Medium-value order' AS order_category;
ELSE
SELECT 'Low-value order' AS order_category;
END IF;
END //
DELIMITER ;
Test the procedure:
CALL CheckOrderAmount(12000);
CALL CheckOrderAmount(5000);
CALL CheckOrderAmount(500);
The procedure returns a different category based on the supplied amount.
14. Loops in Stored Programs
Loops repeat a set of statements while a specified condition or loop rule allows execution to continue. They can be useful for iterative processing, although set-based SQL operations are often more efficient for bulk database work.
14.1 WHILE Loop
WHILE condition DO
statements;
END WHILE;
14.2 Example: Displaying Numbers from 1 to 5
DELIMITER //
CREATE PROCEDURE DisplayNumbers()
BEGIN
DECLARE v_number INT DEFAULT 1;
WHILE v_number <= 5 DO
SELECT v_number AS current_number;
SET v_number = v_number + 1;
END WHILE;
END //
DELIMITER ;
Execute it:
CALL DisplayNumbers();
This example illustrates loop syntax. It produces multiple result sets because each iteration executes a separate SELECT statement. For practical applications, returning one result set or using a set-based query is often preferable.
14.3 Loop Safety
- Ensure that the loop condition can eventually become false.
- Update loop-control variables correctly.
- Avoid unnecessary row-by-row operations when one SQL statement can perform the same task.
- Test loops using small data sets before running them against production data.
15. Cursors in Stored Programs
A cursor allows a stored program to process rows from a query result one row at a time. Cursors can be useful when individual row processing is necessary and cannot reasonably be expressed as a set-based operation.
A cursor typically involves declaring the cursor, opening it, fetching rows, handling the end of the result set, and closing the cursor.
Basic Cursor Structure
BEGIN
DECLARE v_finished BOOLEAN DEFAULT FALSE;
DECLARE v_customer_id INT;
DECLARE customer_cursor CURSOR FOR
SELECT customer_id FROM customers;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET v_finished = TRUE;
OPEN customer_cursor;
customer_loop: LOOP
FETCH customer_cursor INTO v_customer_id;
IF v_finished THEN
LEAVE customer_loop;
END IF;
-- Perform required row-level processing here.
END LOOP;
CLOSE customer_cursor;
END
This is a structural example intended to be used inside an appropriate stored-program definition. Cursor declarations and handlers must follow MySQL's declaration-order rules. Variables and conditions are declared before cursors, and cursors before handlers.
16. Error Handling and Condition Handlers
Error handling allows a stored program to respond to certain conditions raised during execution. MySQL provides handlers for conditions such as SQL exceptions and the end of a cursor result set.
16.1 Handler Types
| Handler Type |
Purpose |
| CONTINUE |
Executes the handler and continues execution after the condition is handled. |
| EXIT |
Executes the handler and exits the compound statement block in which the handler is declared. |
16.2 Example of an Exception Handler
DELIMITER //
CREATE PROCEDURE ExampleErrorHandler()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT 'An SQL exception occurred' AS error_message;
END;
SELECT * FROM table_that_does_not_exist;
END //
DELIMITER ;
This example illustrates the structure of an exception handler. Because the referenced table does not exist, execution raises an SQL exception and invokes the EXIT handler. In production, handlers should be designed to preserve useful diagnostic information and apply the intended transaction or rollback policy rather than merely hiding errors.
17. Transactions Within Stored Programs
A transaction groups database operations into a logical unit of work. Transactions are useful when several changes must succeed or fail together.
For transactional tables such as InnoDB tables, common transaction statements include START TRANSACTION, COMMIT, and ROLLBACK.
Example of Transaction Logic
START TRANSACTION;
UPDATE accounts
SET balance = balance - 500
WHERE account_id = 1;
UPDATE accounts
SET balance = balance + 500
WHERE account_id = 2;
COMMIT;
The example transfers 500 units from one account to another. In a real banking application, additional validation is necessary, including checking that the source account exists, has sufficient funds, and is updated exactly as expected. Error handling must also ensure that a failed operation does not leave an incomplete transfer.
Transaction statements should be used carefully inside stored programs because transaction behavior interacts with the calling application's transaction boundaries and MySQL's transaction rules. A transaction design should clearly establish which layer is responsible for committing or rolling back work.
18. Creating and Managing Stored Programs
MySQL provides statements to create, inspect, alter, and remove stored program objects. The exact statement depends on the object type.
| Task |
Stored Procedure |
Stored Function |
Trigger |
Event |
| Create |
CREATE PROCEDURE |
CREATE FUNCTION |
CREATE TRIGGER |
CREATE EVENT |
| Inspect definition |
SHOW CREATE PROCEDURE |
SHOW CREATE FUNCTION |
SHOW CREATE TRIGGER |
SHOW CREATE EVENT |
| Remove |
DROP PROCEDURE |
DROP FUNCTION |
DROP TRIGGER |
DROP EVENT |
MySQL does not provide a general ALTER statement for replacing the body of a stored procedure or stored function in the same way a table definition may be altered. A common approach is to recreate the routine using an appropriate DROP and CREATE workflow, or a supported CREATE OR REPLACE form where available for the specific object and server version. Always check the syntax for the MySQL version being used.
18.1 Inspecting a Procedure
SHOW CREATE PROCEDURE DisplayCustomers;
18.2 Inspecting a Function
SHOW CREATE FUNCTION CalculateDiscount;
18.3 Listing Routines
SELECT ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = DATABASE();
This query lists stored routines associated with the current database. Stored routines include procedures and functions, but not triggers or events.
19. Stored Program Security and Permissions
Stored programs can help centralize database access, but their security depends on how privileges and execution contexts are configured.
Important Security Concepts
- CREATE ROUTINE: A privilege used for creating stored procedures and functions.
- EXECUTE: A privilege that allows an account to execute a routine when granted appropriately.
- TRIGGER: A privilege relevant to creating triggers.
- EVENT: A privilege relevant to creating scheduled events.
- DEFINER: Identifies the account associated with the stored object's definition and security context.
- SQL SECURITY: For stored routines, specifies whether execution uses the definer's or invoker's privileges, subject to MySQL's rules.
Example of Granting Execution Permission
GRANT EXECUTE ON PROCEDURE shop_db.DisplayCustomers
TO 'app_user'@'localhost';
This example grants execution permission for a specific procedure. The account issuing the GRANT statement must have the required administrative privileges. Use the correct account name, host, and database object for your environment.
Security Best Practices
- Grant only the permissions required for each application or user.
- Avoid granting broad administrative privileges to routine callers.
- Review DEFINER accounts and SQL SECURITY settings carefully.
- Validate input values before performing sensitive database operations.
- Use parameterized calls and appropriate application-side protections.
- Do not expose confidential data through unnecessary result sets or error messages.
20. Advantages of Stored Programs
- Reusability: Common database logic can be written once and used by multiple callers.
- Centralized rules: Shared database operations can be managed in one location.
- Reduced network traffic: Applications can invoke a routine rather than sending each SQL statement separately.
- Access control: Properly configured routines can allow controlled database operations without granting direct access to every underlying table.
- Automation: Triggers and events can automate specific database activities.
- Maintainability: Well-organized routines can make complex database workflows easier to understand.
- Consistency: Different applications can use the same centralized implementation of a business operation.
21. Limitations and Challenges
- Debugging complexity: Debugging database-side procedural logic can be more difficult than debugging application code.
- Server resource usage: Complex routines increase work performed by the database server.
- Portability: Stored program syntax and behavior can vary across database platforms.
- Hidden business logic: Applications may become harder to understand if important rules are spread across procedures, triggers, and events.
- Version management: Routine definitions must be included in deployment and source-control workflows.
- Restrictions: MySQL imposes specific limitations on stored functions, triggers, cursors, transactions, and other constructs.
- Operational dependencies: Scheduled events depend on scheduler configuration, while routines and triggers depend on appropriate privileges and object definitions.
22. Stored Programs vs Ordinary SQL Queries
| Feature |
Ordinary SQL Query |
Stored Program |
| Storage |
Often sent by the application when needed. |
Definition is stored in the database. |
| Reuse |
May need to be repeated in application code. |
Can be invoked or activated repeatedly. |
| Programming logic |
Usually represents a particular SQL operation. |
Can combine SQL with supported procedural constructs. |
| Invocation |
Sent as a query or statement. |
Called directly or activated by its event mechanism. |
| Maintenance |
May be maintained in application source code. |
Requires database-object versioning and deployment. |
| Best suited for |
Direct retrieval and modification of data. |
Reusable database operations, automation, and selected business rules. |
23. Practical Example: Customer Management Procedure
Consider a database that contains a customers table. The objective is to create a reusable procedure that retrieves customers from a specified city.
Step 1: Create a Sample Table
CREATE TABLE customers (
customer_id INT AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(100) NOT NULL,
email VARCHAR(150),
city VARCHAR(100)
);
Step 2: Insert Sample Records
INSERT INTO customers (customer_name, email, city)
VALUES
('Aarav Sharma', '[email protected]', 'Mumbai'),
('Diya Patel', '[email protected]', 'Pune'),
('Rohan Mehta', '[email protected]', 'Mumbai');
Step 3: Create the Stored Procedure
DELIMITER //
CREATE PROCEDURE GetCustomersByCity(IN p_city VARCHAR(100))
BEGIN
SELECT customer_id, customer_name, email, city
FROM customers
WHERE city = p_city
ORDER BY customer_name;
END //
DELIMITER ;
Step 4: Execute the Procedure
CALL GetCustomersByCity('Mumbai');
Expected Result
The exact auto-generated IDs depend on the state of the table. This example demonstrates how a single procedure can be reused for different city values without rewriting the query.
24. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Syntax error near END |
Missing semicolon, incorrect block structure, or invalid statement ordering. |
Review the BEGIN...END block and the routine syntax. |
| Routine creation fails around semicolons |
The client delimiter was not changed correctly. |
Use a suitable delimiter in clients that support DELIMITER. |
| Procedure does not exist |
Wrong database, name, or missing routine definition. |
Check the current database and use SHOW PROCEDURE STATUS or INFORMATION_SCHEMA.ROUTINES. |
| Access denied |
The account lacks the necessary privilege. |
Ask an authorized administrator to review the relevant grants. |
| Function cannot be used as expected |
Return type, characteristics, or stored-function restrictions are incorrect. |
Review the function definition and MySQL documentation. |
| Trigger does not execute |
The triggering table operation did not occur, or the trigger is associated with a different table/event. |
Inspect the trigger definition and test the relevant INSERT, UPDATE, or DELETE. |
| Scheduled event does not run |
The Event Scheduler is disabled or the schedule has not been reached. |
Check event_scheduler and inspect the event definition and status. |
| Unexpected result set |
Multiple SELECT statements return separate result sets. |
Design the routine to return the intended result structure. |
25. Best Practices for Stored Programs
- Use descriptive names such as
GetCustomerById and CalculateDiscount.
- Give each procedure or function a clear responsibility.
- Use parameters instead of hard-coded values wherever possible.
- Choose appropriate data types and lengths for parameters and local variables.
- Validate values before using them in sensitive operations.
- Use set-based SQL statements instead of cursors or loops when possible.
- Implement error handling that supports correct recovery and diagnosis.
- Design transaction boundaries carefully and test rollback behavior.
- Document important business rules and assumptions.
- Test routines using normal, boundary, and invalid inputs.
- Review execution plans and indexing when routines contain expensive queries.
- Manage routine definitions through source control and repeatable deployment scripts.
- Review permissions and execution security settings before production deployment.
- Avoid unnecessary triggers that make database changes difficult to trace.
- Monitor scheduled events and make their operations safe to repeat when appropriate.
26. Mini Project: Order Processing System
Project objective: Create a simple database workflow using a stored procedure, a stored function, and a trigger.
Project Requirements
- Create an orders table containing order ID, customer ID, order amount, and order status.
- Create a stored function that calculates a discount for an order.
- Create a stored procedure that retrieves orders for a particular customer.
- Create an audit table to record relevant order changes.
- Create a trigger that records an update to an order's status.
- Test the solution with multiple customers and order records.
- Verify that the output and audit records are correct.
- Document the database objects and their purpose.
Sample Orders Table
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
order_amount DECIMAL(10,2) NOT NULL,
order_status VARCHAR(30) NOT NULL DEFAULT 'Pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Example Procedure for Retrieving Orders
DELIMITER //
CREATE PROCEDURE GetOrdersByCustomer(IN p_customer_id INT)
BEGIN
SELECT order_id, customer_id, order_amount, order_status, created_at
FROM orders
WHERE customer_id = p_customer_id
ORDER BY created_at DESC;
END //
DELIMITER ;
Execute the procedure using a valid customer ID:
CALL GetOrdersByCustomer(101);
Expected learning outcome: Learners will understand how different stored program types can work together to support a database application's requirements. The project is a learning example and should be expanded with validation, appropriate foreign keys, permissions, and error handling before production use.
27. Practice Exercises
- Define stored programs and explain their purpose in MySQL.
- List the four main types of stored programs.
- Create a stored procedure that displays all products from a products table.
- Create a procedure that accepts an employee ID and retrieves the employee's details.
- Create a stored function that calculates 18 percent tax on a supplied amount.
- Explain the difference between IN, OUT, and INOUT parameters.
- Create a trigger that records a new row inserted into a sample table.
- Describe how an event differs from a trigger.
- Write a WHILE loop that counts from 1 to 10.
- Explain why an EXIT handler may be useful.
- Use SHOW CREATE PROCEDURE to inspect a procedure's definition.
- Explain two security risks associated with poorly configured stored programs.
- Describe why set-based SQL is often preferable to processing rows individually.
- Explain the role of the MySQL Event Scheduler.
- Design a small project using at least two types of stored programs.
28. Interview Questions and Answers
Q1. What is a stored program in MySQL?
A stored program is a database object containing SQL statements and supported programming logic stored on the server for later execution or automatic activation.
Q2. What are the main types of stored programs?
The main types are stored procedures, stored functions, triggers, and events.
Q3. What is a stored procedure?
A stored procedure is a named collection of SQL statements invoked explicitly, usually through the CALL statement.
Q4. What is a stored function?
A stored function is a routine that declares a return type and returns a value using RETURN. It can be called within suitable SQL expressions.
Q5. What is the difference between a procedure and a function?
A procedure is invoked with CALL and can perform multi-step operations or return result sets and output parameters. A function returns a value that can be used in an expression.
Q6. What is a trigger?
A trigger is a stored program associated with a table that runs automatically when its configured INSERT, UPDATE, or DELETE event occurs.
Q7. What is an event in MySQL?
An event is a stored object that executes SQL statements according to a schedule managed by the MySQL Event Scheduler.
Q8. Why is DELIMITER used?
In clients that support it, DELIMITER changes the command terminator so semicolons inside a stored program do not end the outer CREATE statement prematurely.
Q9. What is the purpose of BEGIN and END?
BEGIN and END define a compound statement block that can group multiple statements within a stored program.
Q10. What is an IN parameter?
An IN parameter passes a value from the caller into a stored procedure.
Q11. What is an OUT parameter?
An OUT parameter allows a procedure to return a value through a parameter supplied by the caller.
Q12. What is an INOUT parameter?
An INOUT parameter provides an initial value to the procedure and can return a modified value.
Q13. What is a cursor?
A cursor enables a stored program to fetch and process rows from a query result one at a time.
Q14. What is a condition handler?
A condition handler defines how a stored program responds to a specified condition, such as an SQL exception or the end of a cursor result.
Q15. How can you view a procedure's definition?
Use SHOW CREATE PROCEDURE procedure_name; with an appropriate procedure name and the required privileges.
Q16. Can stored programs improve performance?
They can reduce repeated application-to-server communication and centralize operations, but they do not guarantee faster execution. Query design, indexing, workload distribution, and server resources still matter.
Q17. Why are stored functions subject to restrictions?
Functions may execute within expressions and statements, so MySQL restricts certain operations to preserve expected execution behavior and consistency.
Q18. What is the purpose of a trigger audit table?
An audit table stores selected information about database changes, such as the affected record, action, and timestamp.
Q19. What happens if the Event Scheduler is disabled?
Scheduled events will not execute while the scheduler is disabled, even if their definitions exist in the database.
Q20. What are the best practices for stored programs?
Use meaningful names, focused logic, proper parameters, careful error handling, least-privilege permissions, adequate testing, and source-controlled deployment scripts.
29. Quick Revision Notes
- Stored programs keep reusable SQL logic in the database server.
- Stored procedures are created with CREATE PROCEDURE and invoked using CALL.
- Stored functions are created with CREATE FUNCTION and return values.
- Triggers respond automatically to configured table events.
- Events execute according to schedules managed by the Event Scheduler.
- IN, OUT, and INOUT describe procedure parameter modes.
- BEGIN and END group multiple statements into a compound block.
- DECLARE defines local variables, cursors, and handlers where permitted.
- IF statements support conditional execution.
- WHILE and other supported loops repeat statements.
- Cursors process query results one row at a time.
- Condition handlers manage specified SQL conditions.
- Transactions can help coordinate related changes when used correctly.
- SHOW CREATE statements help inspect stored object definitions.
- Permissions, validation, testing, and deployment management are essential for reliable stored programs.
30. Important MySQL Commands
| Command |
Purpose |
CREATE PROCEDURE |
Creates a stored procedure. |
CALL procedure_name() |
Executes a stored procedure. |
CREATE FUNCTION |
Creates a stored function. |
CREATE TRIGGER |
Creates a trigger associated with a table. |
CREATE EVENT |
Creates a scheduled event. |
SHOW CREATE PROCEDURE name |
Displays a procedure definition. |
SHOW CREATE FUNCTION name |
Displays a function definition. |
SHOW TRIGGERS |
Lists triggers visible in the current database context. |
SHOW EVENTS |
Lists events in the current database context. |
DROP PROCEDURE name |
Removes a stored procedure. |
DROP FUNCTION name |
Removes a stored function. |
DROP TRIGGER name |
Removes a trigger. |
DROP EVENT name |
Removes a scheduled event. |
31. Conclusion
Stored programs are an important feature of MySQL because they make it possible to keep reusable database logic on the server. Stored procedures support multi-step operations, stored functions return reusable values, triggers respond to table changes, and events automate scheduled work.
Understanding these objects helps database developers create applications with more consistent database operations, controlled access, and maintainable logic. Successful implementation requires correct syntax, careful testing, secure privileges, appropriate error handling, and a clear strategy for managing database object definitions.
To learn more about MySQL and related database topics, visit the JustAcademy MySQL Training Course or register for a course demo.
32. Additional Learning Resources